<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>资源管理器</title>
  <style>
    canvas {
      border: 1px solid #000;
    }
  </style>
</head>

<body>
  <canvas id="myCanvas" width="600" height="500"></canvas>

  <script>
    // 游戏类
    function Game() {
      this.dom = document.querySelector("#myCanvas");
      this.ctx = this.dom.getContext("2d");
      this.count = 0;

      // 添加属性: 保存需要的图片地址
      this.R = {
        "guGong": "./img/PEN1.png",
        "niaoChao": "./img/PEN2.png",
        "yiHeYuan": "./img/PEN3.png",
        "tianTan": "./img/PEN4.png",
        "guoJianDaJuYuan": "./img/PEN5.png",
      };

      // 获取资源图片的总数
      const self = this;
      const resource = Object.keys(this.R);
      const len = resource.length;

      // 遍历对象 获取每一个key对应的value
      for (let key in this.R) {
        // 备份每一张图片地址
        const src = this.R[key];
        // 创建一个图片
        this.R[key] = new Image();
        // 赋值图片src地址
        this.R[key].src = src;

        // 判断图片是否加载完成 如果完成了 计算器+1 直到加载的完毕的数量与总数量相同, 说明资源加载完毕
        this.R[key].onload = function () {
          self.count++;
          // 清屏
          self.ctx.clearRect(0, 0, 600, 500);
          self.ctx.font = "16px Arial";
          // 设置资源加载文案
          self.ctx.fillText(`图片已经加载: ${self.count}/${len}`, 10, 50);
          // 资源加载完毕 调用开始
          if (self.count == len) {
            self.start();
          }
        };
      }
    }


    // 开始游戏
    Game.prototype.start = function () {
      const self = this;
      self.ctx.drawImage(self.R["guGong"], 100, 100);
    };

    new Game();
  </script>
</body>

</html>